﻿/****************************************
 *  copyright (c) 2008 leo shen
 *  
 *  all rights reserved         
 * 
 *  e-mail : syl.lucky@gmail.com
 * *************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using DotUpdater.Core.Versions;

namespace DotUpdater.Core.VersionGeters
{
    public class LocalVersionGeter : IVersionGeter
    {
        ProgramVersion m_version;
        string m_localAppPath;

        public LocalVersionGeter(string localVersion, string localAppPath)
        {
            m_version = new ProgramVersion(new Version(localVersion));
            m_localAppPath = localAppPath;
        }

        #region IVersionGeter Members

        public DotUpdater.Core.Versions.IVersion GetVersion()
        {
            return m_version;
        }

        public App_Folder GetAppFolderAndFiles()
        {
            DirectoryInfo parentDir = new DirectoryInfo(System.IO.Path.Combine(System.Environment.CurrentDirectory, m_localAppPath));
            App_Folder parentFolder = new App_Folder("app");
            generateFolderAndFiles(parentDir, parentFolder, string.Empty);
            return parentFolder;
        }

        void generateFolderAndFiles(DirectoryInfo parentDir, App_Folder parentFolder, string preName)
        {
            foreach (DirectoryInfo dir in parentDir.GetDirectories())
            {
                App_Folder folder = new App_Folder(preName + dir.Name);
                parentFolder.SubFolders.Add(folder);
                generateFolderAndFiles(dir, folder, folder.Name + @"\");                
            }
            foreach (FileInfo file in parentDir.GetFiles())
            {
                IVersion ver;
                if (file.Extension.ToLower().Equals(".exe") || file.Extension.ToLower().Equals(".dll"))
                {
                    System.Diagnostics.FileVersionInfo diaFileInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(file.FullName);
                    ver = new ProgramVersion(diaFileInfo.FileMajorPart, diaFileInfo.FileMinorPart, diaFileInfo.FileBuildPart, diaFileInfo.FilePrivatePart);
                }
                else
                {
                    ver = new LastModifiedVersion(file.LastWriteTime);
                }
                App_File fileInfo = new App_File(preName + file.Name, ver);
                parentFolder.Files.Add(fileInfo);
            }
        }

        #endregion
    }
}
